package com.egan.pet.admin.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egan.pet.admin.constant.MessageConstant;
import com.egan.entity.dto.LoginFormDTO;
import com.egan.entity.po.User;
import com.egan.pet.admin.repository.mapper.UserMapper;
import com.egan.pet.admin.result.Result;
import com.egan.pet.admin.service.AuthService;
import com.egan.pet.admin.service.IUserService;
import com.egan.pet.admin.utils.HttpUtils;
import com.egan.pet.admin.utils.RegexUtils;
import com.egan.pet.exception.AccountNotFoundException;
import com.egan.pet.exception.PasswordErrorException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.egan.pet.admin.constant.RedisConstants.*;
import static com.egan.pet.admin.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author egan
 * @since 2024-09-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AuthService authService;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合，返回错误信息
            return Result.error("手机号格式错误!");
        }
        //3.符合生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.保存到session
        //session.setAttribute("code",code);
        //4.使用redis代替session
        /*
         *   key是phone value code
         *   加上业务前缀，"login:code:"
         *   2,TimeUnit.MINUTES设置有效期
         */
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码
        log.error("验证码：" + code);

        //增加给手机发验证码 发送短信
        //TODO
//        sendCode(phone, code);
        //返回ok

        return Result.success();
    }

    @Override
    public Result login(LoginFormDTO loginFormDTO, HttpSession session) {
        //全局变量
        String code = loginFormDTO.getCode();
        //1.校验手机号
        String phone = loginFormDTO.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合，返回错误信息
            return Result.error("手机号格式错误!");
        }
        //2.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !cacheCode.equals(code)) {
            //3.不一致直接报错
            return Result.error("验证码错误");
        }
        //4.一致，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //5.判断是否存在
        if (user == null) {
            //6.不存在,创建新的用户并且保存
            user = createUserWithPhone(phone);
        }
//        //7.保存用户信息到session
//        //TODO 7.保存用户信息到Redis
//        //7.1 随机生成TOKEN
//        String token = UUID.randomUUID().toString(true);
//        //7.2 将User对象转为HashMap存储
//        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
//        //7.3 存储
//        String tokenKey = LOGIN_USER_KEY + token;
//        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
//        //session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
//        //7.4 设置token的有效期
//        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
//        //8 返回Token
//        return Result.success(token);

        String token = authService.generateAndSaveToken(user);
        return Result.success(token);
    }

    @Override
    public User loginToPass(LoginFormDTO loginFormDTO) {
        String phone = loginFormDTO.getPhone();
        String password = loginFormDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByPhone(phone);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的密码进行md5处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        authService.generateAndSaveToken(user);
        return user;
    }

    private static void sendCode(String phone, String code) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "2effb0c7a439421680ec62818e6ab16d";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:" + code);
        querys.put("smsSignId", "9c86b86cb495483fb686bd41603db506");
        querys.put("templateId", "517cc1d5d287419c9f492b0c54a11bc9");
        Map<String, String> bodys = new HashMap<String, String>();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private User createUserWithPhone(String phone) {
        //1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(12));
        //2.保存用户
        save(user);
        return user;
    }
}
